package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.ArrayList;

@Service
@Slf4j
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;


    //更新员工
    @Override
    public void updateEmp(EmployeeDTO employeeDTO) {

        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);

//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setUpdateUser(BaseContext.getCurrentId());

        employeeMapper.update(employee);
    }

    //根据ID查询员工
    @Override
    public Employee getById(Long id) {
        Employee employee = employeeMapper.getById(id);
        employee.setPassword("臭不要脸的，在这就像修改密码");
        return employee;
    }

    @Override
    public void getEmpStatus(Integer status, Long id) {
        Employee employee = Employee.builder()
                            .status(status)
                            .id(id)
                            .build();
        employeeMapper.update(employee);
    }

    @Override
    public void addEmp(EmployeeDTO employeeDTO) {
        // 调用emp mapper保持员工
        // 写数据库之前，准备数据，准备完之后写数据库
        // 员工表需要插入11个数据，前端传5给数据，我们需要准备6个
        log.info("[当前线程]，thread:{}",Thread.currentThread().getId());
        Integer status = 1;
        LocalDateTime createTime = LocalDateTime.now();
        LocalDateTime updateTime = LocalDateTime.now();
        // 创建人和更新人的ID（当前登录用户的ID），从token中获取
        // todo 稍后处理如何从token中获取ID，默认是1
        Long empId = BaseContext.threadLocalEmpId.get();
        String username = BaseContext.threadLocalEmpUserName.get();
        log.info("[当前线程]，thread:{} empId:{},empUsername:{}",Thread.currentThread().getId(),empId,username);
        Long createUser = empId;
        Long updateUser = empId;
        // 把前端数据和准备的数据封装成功 实体类对象
        Employee employee = new Employee();
        employee.setName(employeeDTO.getName());
        employee.setUsername(employeeDTO.getUsername());
        employee.setIdNumber(employeeDTO.getIdNumber());
        employee.setSex(employeeDTO.getSex());
        employee.setPhone(employeeDTO.getPhone());
        employee.setStatus(status);


//        employee.setCreateTime(createTime);
//        employee.setUpdateTime(updateTime);
//        employee.setCreateUser(createUser);
//        employee.setUpdateUser(updateUser);
// 思路：使用AOP，创建一个切面，切面的切入点拦截是Service的方法还是Mapper的方法
        // 我们目的是就是在写数据库之前，不用自己给功能字段填充数据


        //默认密码是123456
        String md5Password = DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes());
        employee.setPassword(md5Password);
        // 调用mapper
        employeeMapper.insertEmp(employee);
        log.info("emp:{}",employee);
    }

    @Override
    public PageResult findByPage(EmployeePageQueryDTO employeePageQueryDTO) {
        //调用mapper
        //使用分页插件
        //分页插件帮我们动态分页，计算记录数和结果集
        PageHelper.startPage(employeePageQueryDTO.getPage(),employeePageQueryDTO.getPageSize());
        Page<Employee> employeePage = employeeMapper.selectByPageAndName(employeePageQueryDTO.getName());

        PageResult pageResult = new PageResult(employeePage.getTotal(),employeePage.getResult());
        return pageResult;
    }


    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // 进行md5加密，然后再进行比对
        String md5password = DigestUtils.md5DigestAsHex(password.getBytes());
        log.info("Dd5Password:{}",md5password);
        if (!md5password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

}
